package com.doublefish.doublefishrobot.ui.video;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;

import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.video.bean.VideoPlayerItemBean;
import com.doublefish.doublefishrobot.ui.video.utils.Uri2FileUtils;
import com.doublefish.doublefishrobot.ui.video.widget.VideoChooseToolView;
import com.doublefish.doublefishrobot.ui.video.widget.VideoPlayerView;
import com.doublefish.doublefishrobot.widget.ActionListDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/10/29 14:53
 */
public class VideoContrastActivity extends BaseActivity {

    @BindView(R.id.view_top)
    ViewGroup topView;

    @BindView(R.id.tv_title)
    TextView titleTv;

    @BindView(R.id.toolview0)
    VideoChooseToolView toolView0;
    @BindView(R.id.fl_video0)
    FrameLayout videoFl0;
    @BindView(R.id.view_video_content0)
    VideoPlayerView videoPlayerView0;

    @BindView(R.id.toolview1)
    VideoChooseToolView toolView1;
    @BindView(R.id.fl_video1)
    FrameLayout videoFl1;
    @BindView(R.id.view_video_content1)
    VideoPlayerView videoPlayerView1;

    private String videoCode;
    private String videoPath;       //48种训练模式的视频路径

    private String localVideoPath;  //本地视频路径

    private int isFullScreen = 0;  //0.非全屏 1.上面的播放器视图 2.下面的播放器视图

    private int  REQUEST_CODE_GALLERY = 66;   //从相册选择视频
    private int  REQUEST_CODE_EDIT_SYS = 77;  //对内置模式视频进行编辑
    private int  REQUEST_CODE_EIDT_CUS = 88;  //对自选的视频进行编辑


    public static Intent createIntent(Context context, String videoName, String videoCode, String videoPath) {
        Intent intent = new Intent(context, VideoContrastActivity.class);
        intent.putExtra("videoName", videoName);
        intent.putExtra("videoCode", videoCode);
        intent.putExtra("videoPath", videoPath);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_video_contrast;
    }

    @Override
    protected void initView() {
        titleTv.setText(R.string.video_contrast);
        layoutViews();
    }

    @Override
    protected void initListener() {
        videoPlayerView0.setOnVideoPalyerViewListner(new VideoPlayerView.OnVideoPalyerViewListner() {
            @Override
            public void onFullScreenBtnClick(boolean fullScreen) {
                if (fullScreen) {
                    setFullscreen(1);
                } else {
                    setFullscreen(0);
                }
            }

            @Override
            public void onSpeedBtnClick() {
                showSpeedDialog(videoPlayerView0);
            }
        });
        videoPlayerView1.setOnVideoPalyerViewListner(new VideoPlayerView.OnVideoPalyerViewListner() {
            @Override
            public void onFullScreenBtnClick(boolean fullScreen) {
                if (fullScreen) {
                    setFullscreen(2);
                } else {
                    setFullscreen(0);
                }
            }

            @Override
            public void onSpeedBtnClick() {
                showSpeedDialog(videoPlayerView1);
            }
        });

        toolView0.setOnVideoChooseToolViewListner(new VideoChooseToolView.OnVideoChooseToolViewListner() {
            @Override
            public void onChooseVideoCallback() {

            }

            @Override
            public void onEditVideoCallback() {
                if (videoPath == null || videoPath.length() == 0) {
                    return;
                }
                editVideo(videoPath, REQUEST_CODE_EDIT_SYS);
            }
        });

        toolView1.setOnVideoChooseToolViewListner(new VideoChooseToolView.OnVideoChooseToolViewListner() {
            @Override
            public void onChooseVideoCallback() {
                chooseVideo();
            }

            @Override
            public void onEditVideoCallback() {
                if (localVideoPath == null || localVideoPath.length() == 0) {
                    return;
                }
                editVideo(localVideoPath, REQUEST_CODE_EIDT_CUS);
            }
        });
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        String videoName = intent.getStringExtra("videoName");
        videoPath = intent.getStringExtra("videoPath");
        videoCode = intent.getStringExtra("videoCode");

        toolView0.setName(videoName);
        toolView1.setName(getString(R.string.local_video));
        toolView0.setChooseTvVisibility(false);
        toolView1.setChooseTvVisibility(true);

        //准备播放
        VideoPlayerItemBean bean = new VideoPlayerItemBean(VideoPlayerItemBean.DFAVPlayerItemLocal, null, videoPath,0, 0);
        videoPlayerView0.setVideoPlayerItemBean(bean);
    }

    @Override
    protected void onDestroy() {
        if (videoPlayerView0 != null) {
            videoPlayerView0.stop();
        }
        if (videoPlayerView1 != null) {
            videoPlayerView1.stop();
        }
        unRegisterSensorManager();
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        layoutViews();
    }

    private void setFullscreen(int fullScreen) {
        isFullScreen = fullScreen;
        if (fullScreen != 0) {
            registerSensorManager();
        } else {
            unRegisterSensorManager();
            mFlag = 1;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        layoutViews();
    }

    private void layoutViews() {
        if (isFullScreen == 0) {
            showSystemUI();
            topView.setVisibility(View.VISIBLE);

            toolView0.setVisibility(View.VISIBLE);
            toolView1.setVisibility(View.VISIBLE);
            videoFl0.setVisibility(View.VISIBLE);
            videoFl1.setVisibility(View.VISIBLE);

            //非全屏状态
            DisplayMetrics dm = new DisplayMetrics();//屏幕度量
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenWidth = dm.widthPixels;//宽度
            //调整播放器的大小 使宽高比为16:9
            ViewGroup.LayoutParams layoutParams = videoFl0.getLayoutParams();
            layoutParams.width = screenWidth;
            layoutParams.height = screenWidth * 9 / 16;
            videoFl0.setLayoutParams(layoutParams);

            ViewGroup.LayoutParams layoutParams1 = videoFl1.getLayoutParams();
            layoutParams1.width = screenWidth;
            layoutParams1.height = screenWidth * 9 / 16;
            videoFl1.setLayoutParams(layoutParams1);

        } else if (isFullScreen == 1) {
            topView.setVisibility(View.GONE);
            toolView0.setVisibility(View.GONE);
            toolView1.setVisibility(View.GONE);
            videoFl0.setVisibility(View.VISIBLE);
            videoFl1.setVisibility(View.GONE);

            //全屏状态
            DisplayMetrics dm = new DisplayMetrics();//屏幕度量
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenWidth = dm.widthPixels;//宽度
            int screenHeight = dm.heightPixels;//高度
            if (mFlag == 1) {
                showSystemUI();
            } else if (mFlag == 2 || mFlag == 4) {
                hideSystemUI();
            }
            //调整播放器的大小为全屏
            ViewGroup.LayoutParams layoutParams = videoFl0.getLayoutParams();
            layoutParams.width = screenWidth;
            layoutParams.height = screenHeight;
            videoFl0.setLayoutParams(layoutParams);

        } else if (isFullScreen == 2) {
            topView.setVisibility(View.GONE);
            toolView0.setVisibility(View.GONE);
            toolView1.setVisibility(View.GONE);
            videoFl0.setVisibility(View.GONE);
            videoFl1.setVisibility(View.VISIBLE);
            //全屏状态
            DisplayMetrics dm = new DisplayMetrics();//屏幕度量
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenWidth = dm.widthPixels;//宽度
            int screenHeight = dm.heightPixels;//高度
            if (mFlag == 1) {
                showSystemUI();
            } else if (mFlag == 2 || mFlag == 4) {
                hideSystemUI();
            }
            //调整播放器的大小为全屏
            ViewGroup.LayoutParams layoutParams = videoFl1.getLayoutParams();
            layoutParams.width = screenWidth;
            layoutParams.height = screenHeight;
            videoFl1.setLayoutParams(layoutParams);
        }
    }

    private void showSpeedDialog(VideoPlayerView videoPlayerView) {
        String title = getString(R.string.select_playback_speed);
        List<String> list = videoPlayerView.speedList();

        ActionListDialog dialog = new ActionListDialog(this, title, list, new ActionListDialog.OnActionListDialogListner() {
            @Override
            public void onActionBtnClick(int postion, String text) {
                videoPlayerView.setSpeed(postion);
            }

            @Override
            public void onCancelBtnClick() {

            }
        });
        dialog.show();
    }

    @OnClick(R.id.ll_back)
    public void onBackClick() {
        finish();
    }

    /**
     * 从相册中选择视频
     */
    private void chooseVideo() {
        Intent intentFromGallery = new Intent();
        intentFromGallery.setAction(Intent.ACTION_PICK);
        intentFromGallery.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"video/*" );
//        startActivityForResult(intentFromGallery, REQUEST_CODE_GALLERY);
        startActivityForResult(Intent.createChooser(intentFromGallery, getString(R.string.select_video)), REQUEST_CODE_GALLERY);
    }

    private void editVideo(String path, int requestCode) {
        Intent intent = VideoEditActivity.createIntent(this, path);
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == REQUEST_CODE_GALLERY) {
            Uri uri = data.getData();
            //获取到视频的真实路径
            String path = Uri2FileUtils.getPath(this, uri);
            localVideoPath = path;
            if (path != null) {
                VideoPlayerItemBean bean = new VideoPlayerItemBean(VideoPlayerItemBean.DFAVPlayerItemLocal, null, path,0, 0);
                videoPlayerView1.setVideoPlayerItemBean(bean);
            }
        } else if (requestCode == REQUEST_CODE_EDIT_SYS) {
            Uri uri = data.getData();
            if (uri != null) {
                String path = uri.toString();
                VideoPlayerItemBean bean = new VideoPlayerItemBean(VideoPlayerItemBean.DFAVPlayerItemLocal, null, path,0, 0);
                videoPlayerView0.setVideoPlayerItemBean(bean);
            }
        } else if (requestCode == REQUEST_CODE_EIDT_CUS) {
            Uri uri = data.getData();
            if (uri != null) {
                String path = uri.toString();
                VideoPlayerItemBean bean = new VideoPlayerItemBean(VideoPlayerItemBean.DFAVPlayerItemLocal, null, path,0, 0);
                videoPlayerView1.setVideoPlayerItemBean(bean);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == android.view.KeyEvent.KEYCODE_BACK && isFullScreen != 0) {
            setFullscreen(0);
            if (isFullScreen == 1) {
                videoPlayerView0.exitFullScreen();
            } else {
                videoPlayerView1.exitFullScreen();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //region 重力感应
    private SensorManager sensorManager;
    private Sensor sensor;
    SensorEventListener listener;
    private int mFlag = 1;  //默认1 正常竖屏 （0.无变化\变化小 1.正常竖屏 2.右横屏 3.倒立竖屏 4.左横屏）

    private void registerSensorManager() {
        //使用加速度传感器判断屏幕方向
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        listener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent sensorEvent) {
                float[] values = sensorEvent.values;
                int orientation = 0;
                float X = -values[0];
                float Y = -values[1];
                float Z = -values[2];
                float magnitude = X * X + Y * Y;
                // Don't trust the angle if the magnitude is small compared to the y value
                if (magnitude * 4 >= Z * Z) {
                    float OneEightyOverPi = 57.29577957855f;
                    float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
                    orientation = 90 - (int) Math.round(angle);
                    // normalize to 0 - 359 range
                    while (orientation >= 360) {
                        orientation -= 360;
                    }
                    while (orientation < 0) {
                        orientation += 360;
                    }
                }
                onOrientationChanged(orientation);
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {

            }
        };
        sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
    }

    private void unRegisterSensorManager() {
        if (listener != null) {
            sensorManager.unregisterListener(listener);
            listener = null;
        }
    }

    private void onOrientationChanged(int orientation) {
        int flag = 0;
        if (orientation > 0 && orientation < 45) {
            flag = 1;  //正常竖屏
        } else if (orientation > 45 && orientation < 135) {
            flag = 2;  //右横屏
        } else if (orientation > 135 && orientation < 225) {
            flag = 3;  //倒立竖屏
        } else if (orientation > 225 && orientation < 315) {
            flag = 4;  //左横屏
        } else if (orientation > 315 && orientation < 360) {
            flag = 1;  //正常竖屏
        }
//        Log.i("OrientationListener","" + orientation);
        //倒立竖屏 不做处理
        if (flag == 1 && mFlag != 1) {
            mFlag = 1;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else if (flag == 2 && mFlag != 2) {
            mFlag = 2;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
        } else if (flag == 4 && mFlag != 4) {
            mFlag = 4;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }


    //全屏

    /**
     * 隐藏系统ui
     */
    private void hideSystemUI() {
        //隐藏ActionBar 如果使用了NoActionBar的Theme则不需要隐藏actionBar
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        //TODO：View.setSystemUiVisibility(int visibility)中，visibility是Mode与Layout任意取值的组合，可传入的实参为：

        // Mode属性
        //View.SYSTEM_UI_FLAG_LOW_PROFILE：状态栏显示处于低能显示状态(low profile模式)，状态栏上一些图标显示会被隐藏。
        //View.SYSTEM_UI_FLAG_FULLSCREEN：Activity全屏显示，且状态栏被隐藏覆盖掉。等同于（WindowManager.LayoutParams.FLAG_FULLSCREEN）
        //View.SYSTEM_UI_FLAG_HIDE_NAVIGATION：隐藏虚拟按键(导航栏)。有些手机会用虚拟按键来代替物理按键。
        //View.SYSTEM_UI_FLAG_IMMERSIVE：这个flag只有当设置了SYSTEM_UI_FLAG_HIDE_NAVIGATION才起作用。
        // 如果没有设置这个flag，任意的View相互动作都退出SYSTEM_UI_FLAG_HIDE_NAVIGATION模式。如果设置就不会退出。
        //View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY：这个flag只有当设置了SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION 时才起作用。
        // 如果没有设置这个flag，任意的View相互动作都坏退出SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION模式。如果设置就不受影响。

        // Layout属性
        //View.SYSTEM_UI_FLAG_LAYOUT_STABLE： 保持View Layout不变，隐藏状态栏或者导航栏后，View不会拉伸。
        //View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN：让View全屏显示，Layout会被拉伸到StatusBar下面，不包含NavigationBar。
        //View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION：让View全屏显示，Layout会被拉伸到StatusBar和NavigationBar下面。
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LOW_PROFILE
//                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                            | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            );
        }
        //解决在华为手机上横屏时，状态栏不消失的问题
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏

    }

    /**
     * 显示系统UI
     */
    private void showSystemUI() {
        //显示ActionBar 如果使用了NoActionBar的Theme则不需要显示actionBar
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.show();
        }
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            // This snippet shows the system bars. It does this by removing all the flags
            // except for the ones that make the content appear under the system bars.
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
        //解决在华为手机上横屏时，状态栏不消失的问题
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //显示状态栏
    }


    //endregion
}

